<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单用户" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入下单用户"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址id" prop="addressBookId">
        <el-input
          v-model="queryParams.addressBookId"
          placeholder="请输入地址id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable
          v-model="queryParams.orderTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结账时间" prop="checkoutTime">
        <el-date-picker clearable
          v-model="queryParams.checkoutTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择结账时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实收金额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入实收金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单人" prop="consignee">
        <el-input
          v-model="queryParams.consignee"
          placeholder="请输入下单人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单取消原因" prop="cancelReason">
        <el-input
          v-model="queryParams.cancelReason"
          placeholder="请输入订单取消原因"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单拒绝原因" prop="rejectionReason">
        <el-input
          v-model="queryParams.rejectionReason"
          placeholder="请输入订单拒绝原因"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单取消时间" prop="cancelTime">
        <el-date-picker clearable
          v-model="queryParams.cancelTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择订单取消时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预计送达时间" prop="estimatedDeliveryTime">
        <el-date-picker clearable
          v-model="queryParams.estimatedDeliveryTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预计送达时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="菜品完成时间" prop="deliveryTime">
        <el-date-picker clearable
          v-model="queryParams.deliveryTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择菜品完成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="打包费" prop="packAmount">
        <el-input
          v-model="queryParams.packAmount"
          placeholder="请输入打包费"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="餐具数量" prop="tablewareNumber">
        <el-input
          v-model="queryParams.tablewareNumber"
          placeholder="请输入餐具数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['merchant:orders:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['merchant:orders:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['merchant:orders:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['merchant:orders:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="订单号" align="center" prop="number" />
      <el-table-column label="订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款" align="center" prop="status" />
      <el-table-column label="下单用户" align="center" prop="userId" />
      <el-table-column label="地址id" align="center" prop="addressBookId" />
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结账时间" align="center" prop="checkoutTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkoutTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式 1微信,2支付宝" align="center" prop="payMethod" />
      <el-table-column label="支付状态 0未支付 1已支付 2退款" align="center" prop="payStatus" />
      <el-table-column label="实收金额" align="center" prop="amount" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="下单人" align="center" prop="consignee" />
      <el-table-column label="订单取消原因" align="center" prop="cancelReason" />
      <el-table-column label="订单拒绝原因" align="center" prop="rejectionReason" />
      <el-table-column label="订单取消时间" align="center" prop="cancelTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.cancelTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预计送达时间" align="center" prop="estimatedDeliveryTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.estimatedDeliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜品状态  1立即送出  0选择具体时间" align="center" prop="deliveryStatus" />
      <el-table-column label="菜品完成时间" align="center" prop="deliveryTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打包费" align="center" prop="packAmount" />
      <el-table-column label="餐具数量" align="center" prop="tablewareNumber" />
      <el-table-column label="餐具数量状态  1按餐量提供  0选择具体数量" align="center" prop="tablewareStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['merchant:orders:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['merchant:orders:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ordersRef" :model="form" :rules="rules" label-width="80px">
        <el-divider content-position="center">订单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddOrderDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteOrderDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="orderDetailList" :row-class-name="rowOrderDetailIndex" @selection-change="handleOrderDetailSelectionChange" ref="orderDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="名字" prop="name" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入名字" />
            </template>
          </el-table-column>
          <el-table-column label="菜品id" prop="dishId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.dishId" placeholder="请输入菜品id" />
            </template>
          </el-table-column>
          <el-table-column label="套餐id" prop="setmealId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.setmealId" placeholder="请输入套餐id" />
            </template>
          </el-table-column>
          <el-table-column label="口味" prop="dishFlavor" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.dishFlavor" placeholder="请输入口味" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="number" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.number" placeholder="请输入数量" />
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.amount" placeholder="请输入金额" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Orders">
import { listOrders, getOrders, delOrders, addOrders, updateOrders } from "@/api/merchant/orders"

const { proxy } = getCurrentInstance()

const ordersList = ref([])
const orderDetailList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedOrderDetail = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: null,
    status: null,
    userId: null,
    addressBookId: null,
    orderTime: null,
    checkoutTime: null,
    amount: null,
    phone: null,
    address: null,
    userName: null,
    consignee: null,
    cancelReason: null,
    rejectionReason: null,
    cancelTime: null,
    estimatedDeliveryTime: null,
    deliveryStatus: null,
    deliveryTime: null,
    packAmount: null,
    tablewareNumber: null,
    tablewareStatus: null
  },
  rules: {
    status: [
      { required: true, message: "订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款不能为空", trigger: "change" }
    ],
    userId: [
      { required: true, message: "下单用户不能为空", trigger: "blur" }
    ],
    addressBookId: [
      { required: true, message: "地址id不能为空", trigger: "blur" }
    ],
    orderTime: [
      { required: true, message: "下单时间不能为空", trigger: "blur" }
    ],
    payMethod: [
      { required: true, message: "支付方式 1微信,2支付宝不能为空", trigger: "blur" }
    ],
    payStatus: [
      { required: true, message: "支付状态 0未支付 1已支付 2退款不能为空", trigger: "change" }
    ],
    amount: [
      { required: true, message: "实收金额不能为空", trigger: "blur" }
    ],
    deliveryStatus: [
      { required: true, message: "菜品状态  1立即送出  0选择具体时间不能为空", trigger: "change" }
    ],
    tablewareStatus: [
      { required: true, message: "餐具数量状态  1按餐量提供  0选择具体数量不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询订单列表 */
function getList() {
  loading.value = true
  listOrders(queryParams.value).then(response => {
    ordersList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    number: null,
    status: null,
    userId: null,
    addressBookId: null,
    orderTime: null,
    checkoutTime: null,
    payMethod: null,
    payStatus: null,
    amount: null,
    remark: null,
    phone: null,
    address: null,
    userName: null,
    consignee: null,
    cancelReason: null,
    rejectionReason: null,
    cancelTime: null,
    estimatedDeliveryTime: null,
    deliveryStatus: null,
    deliveryTime: null,
    packAmount: null,
    tablewareNumber: null,
    tablewareStatus: null
  }
  orderDetailList.value = []
  proxy.resetForm("ordersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getOrders(_id).then(response => {
    form.value = response.data
    orderDetailList.value = response.data.orderDetailList
    open.value = true
    title.value = "修改订单"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordersRef"].validate(valid => {
    if (valid) {
      form.value.orderDetailList = orderDetailList.value
      if (form.value.id != null) {
        updateOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单编号为"' + _ids + '"的数据项？').then(function() {
    return delOrders(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 订单明细序号 */
function rowOrderDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 订单明细添加按钮操作 */
function handleAddOrderDetail() {
  let obj = {}
  obj.name = ""
  obj.image = ""
  obj.dishId = ""
  obj.setmealId = ""
  obj.dishFlavor = ""
  obj.number = ""
  obj.amount = ""
  orderDetailList.value.push(obj)
}

/** 订单明细删除按钮操作 */
function handleDeleteOrderDetail() {
  if (checkedOrderDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的订单明细数据")
  } else {
    const orderDetails = orderDetailList.value
    const checkedOrderDetails = checkedOrderDetail.value
    orderDetailList.value = orderDetails.filter(function(item) {
      return checkedOrderDetails.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleOrderDetailSelectionChange(selection) {
  checkedOrderDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('merchant/orders/export', {
    ...queryParams.value
  }, `orders_${new Date().getTime()}.xlsx`)
}

getList()
</script>
